/**
 * 绘本相关API接口
 */

import type {
  AudioResourceRespVO,
  BatchFavoriteCheckReqVO,
  BookPageRespVO,
  BookSearchParams,
  BookSetDetailRespVO,
  BookSetRespVO,
  BookSetSearchParams,
  CategoryRespVO,
  FavoriteOperationReqVO,
  FavoriteParams,
  FavoriteStatusRespVO,
  PictureBookDetailRespVO,
  PictureBookRespVO,
  RecommendedBookSetsParams,
  UserRecordingRespVO,
} from './types/book'
import type { ApiResponse, PageParams, PageResult } from './types/common'
import { http, httpDeleteWithBody } from '@/utils/request'

/**
 * 获取绘本分类列表
 */
export function getCategoryList(language?: string) {
  // 语言映射：前端使用 english/chinese，后端使用 en/zh
  const languageMap: Record<string, string> = {
    english: 'en',
    chinese: 'zh',
  }

  const apiLanguage = language ? languageMap[language] || language : undefined
  return http.get<CategoryRespVO[]>('/reading/categories/list', { lang: apiLanguage })
}

/**
 * 获取绘本集分页列表
 */
export function getBookSetPage(params: BookSetSearchParams) {
  // 语言映射：前端使用 english/chinese，后端使用 en/zh
  const languageMap: Record<string, string> = {
    english: 'en',
    chinese: 'zh',
  }

  // 转换参数：language -> lang，并进行语言映射
  const apiParams = {
    ...params,
    lang: params.language ? languageMap[params.language] || params.language : undefined,
    language: undefined, // 移除language字段
  }
  return http.get<PageResult<BookSetRespVO>>('/reading/book-sets/page', apiParams)
}

/**
 * 获取绘本集详情
 */
export function getBookSetDetail(id: number) {
  return http.get<BookSetDetailRespVO>(`/reading/book-sets/${id}`)
}

/**
 * 获取推荐绘本集
 */
export function getRecommendedBookSets(params?: RecommendedBookSetsParams) {
  return http.get<BookSetRespVO[]>('/reading/book-sets/recommended', params)
}

/**
 * 搜索绘本集
 */
export function searchBookSets(params: BookSetSearchParams) {
  // 语言映射：前端使用 english/chinese，后端使用 en/zh
  const languageMap: Record<string, string> = {
    english: 'en',
    chinese: 'zh',
  }

  // 转换参数：language -> lang，并进行语言映射
  const apiParams = {
    keyword: params.keyword,
    lang: params.language ? languageMap[params.language] || params.language : undefined,
    pageNo: params.pageNo,
    pageSize: params.pageSize,
  }
  return http.get<PageResult<BookSetRespVO>>('/reading/book-sets/search', apiParams)
}

/**
 * 获取绘本详情
 */
export function getPictureBookDetail(id: number) {
  return http.get<PictureBookDetailRespVO>(`/reading/books/${id}`)
}

/**
 * 获取绘本页面列表
 */
export function getBookPages(bookId: number) {
  return http.get<BookPageRespVO[]>(`/reading/books/${bookId}/pages`)
}

/**
 * 搜索绘本
 */
export function searchBooks(params: BookSearchParams) {
  return http.get<PageResult<PictureBookRespVO>>('/reading/books/search', params)
}

/**
 * 获取绘本音频资源
 */
export function getBookAudio(bookId: number) {
  return http.get<AudioResourceRespVO[]>(`/reading/audio/book/${bookId}`)
}

/**
 * 获取页面音频资源
 */
export function getPageAudio(pageId: number) {
  return http.get<AudioResourceRespVO[]>(`/reading/audio/page/${pageId}`)
}

/**
 * 播放音频（记录播放次数）
 */
export function playAudio(audioId: number) {
  return http.post<boolean>(`/reading/audio/${audioId}/play`)
}

/**
 * 点赞音频
 */
export function likeAudio(audioId: number) {
  return http.post<boolean>(`/reading/audio/${audioId}/like`)
}

/**
 * 取消点赞音频
 */
export function unlikeAudio(audioId: number) {
  return http.delete<boolean>(`/reading/audio/${audioId}/like`)
}

/**
 * 获取用户配音列表
 */
export function getUserRecordings(params: PageParams) {
  return http.get<ApiResponse<PageResult<UserRecordingRespVO>>>('/reading/recordings/my-list', params)
}

/**
 * 获取页面用户配音
 */
export function getPageRecordings(pageId: number) {
  return http.get<ApiResponse<UserRecordingRespVO[]>>(`/reading/recordings/page/${pageId}`)
}

/**
 * 创建用户配音
 */
export function createUserRecording(data: {
  bookId: number
  pageId?: number
  audioUrl: string
  duration: number
  title?: string
  description?: string
  isPublic?: boolean
}) {
  return http.post<ApiResponse<number>>('/reading/recordings/create', data)
}

/**
 * 更新用户配音
 */
export function updateUserRecording(id: number, data: {
  title?: string
  description?: string
  isPublic?: boolean
  status?: string
}) {
  return http.put<ApiResponse<boolean>>(`/reading/recordings/${id}`, data)
}

/**
 * 删除用户配音
 */
export function deleteUserRecording(id: number) {
  return http.delete<ApiResponse<boolean>>(`/reading/recordings/${id}`)
}

/**
 * 点赞用户配音
 */
export function likeUserRecording(id: number) {
  return http.post<ApiResponse<boolean>>(`/reading/recordings/${id}/like`)
}

/**
 * 取消点赞用户配音
 */
export function unlikeUserRecording(id: number) {
  return http.delete<ApiResponse<boolean>>(`/reading/recordings/${id}/like`)
}

// 注意：最近阅读记录相关的API已移至 record.ts 模块

/**
 * 添加绘本收藏
 */
export function addBookFavorite(data: FavoriteOperationReqVO) {
  return http.post<boolean>('/reading/favorites/add', data)
}

/**
 * 取消绘本收藏
 */
export function removeBookFavorite(data: FavoriteOperationReqVO) {
  return httpDeleteWithBody<boolean>('/reading/favorites/remove', data)
}

/**
 * 检查绘本收藏状态
 */
export function checkBookFavoriteStatus(targetId: number, targetType: string) {
  return http.get<boolean>('/reading/favorites/check', { targetId, targetType })
}

/**
 * 批量检查收藏状态
 */
export function batchCheckFavoriteStatus(data: BatchFavoriteCheckReqVO) {
  return http.post<ApiResponse<FavoriteStatusRespVO[]>>('/reading/favorites/batch-check', data)
}

/**
 * 获取收藏列表
 */
export function getFavoriteList(params: FavoriteParams) {
  return http.get<ApiResponse<PageResult<any>>>('/reading/favorites/list', params)
}

/**
 * 获取收藏数量
 */
export function getFavoriteCount(type?: string) {
  return http.get<ApiResponse<number>>('/reading/favorites/count', { type })
}

/**
 * 上传绘本封面
 */
export function uploadBookCover(file: File) {
  const formData = new FormData()
  formData.append('file', file)
  return http.post<ApiResponse<string>>('/reading/books/upload-cover', formData, {
    'Content-Type': 'multipart/form-data',
  })
}

/**
 * 上传绘本页面图片
 */
export function uploadBookPageImage(file: File) {
  const formData = new FormData()
  formData.append('file', file)
  return http.post<ApiResponse<string>>('/reading/books/upload-page-image', formData, {
    'Content-Type': 'multipart/form-data',
  })
}

/**
 * 上传音频文件
 */
export function uploadAudioFile(file: File) {
  const formData = new FormData()
  formData.append('file', file)
  return http.post<ApiResponse<string>>('/reading/audio/upload', formData, {
    'Content-Type': 'multipart/form-data',
  })
}

/**
 * 获取热门搜索关键词
 */
export function getHotSearchKeywords() {
  return http.get<ApiResponse<string[]>>('/reading/search/hot-keywords')
}

/**
 * 记录搜索历史
 */
export function recordSearchHistory(keyword: string) {
  return http.post<ApiResponse<boolean>>('/reading/search/record', { keyword })
}

/**
 * 获取搜索历史
 */
export function getSearchHistory() {
  return http.get<ApiResponse<string[]>>('/reading/search/history')
}

/**
 * 清除搜索历史
 */
export function clearSearchHistory() {
  return http.delete<ApiResponse<boolean>>('/reading/search/history')
}

/**
 * 获取绘本统计信息
 */
export function getBookStats() {
  return http.get<ApiResponse<any>>('/reading/books/stats')
}

/**
 * 翻译文本内容
 */
export function translateText(data: {
  text: string
  sourceLanguage: string
  targetLanguage: string
  bookId?: number
  pageId?: number
}) {
  return http.post<ApiResponse<{
    translatedText: string
    sourceText: string
    sourceLanguage: string
    targetLanguage: string
  }>>('/reading/translation/translate', data)
}

/**
 * 获取翻译历史
 */
export function getTranslationHistory(params: {
  bookId?: number
  pageId?: number
  pageNo?: number
  pageSize?: number
}) {
  return http.get<ApiResponse<PageResult<{
    id: number
    sourceText: string
    translatedText: string
    sourceLanguage: string
    targetLanguage: string
    bookId?: number
    pageId?: number
    createTime: string
  }>>>('/reading/translation/history', params)
}

/**
 * 删除翻译记录
 */
export function deleteTranslation(id: number) {
  return http.delete<ApiResponse<boolean>>(`/reading/translation/${id}`)
}

/**
 * 批量翻译页面内容
 */
export function batchTranslatePage(data: {
  pageId: number
  sourceLanguage: string
  targetLanguage: string
}) {
  return http.post<ApiResponse<{
    pageId: number
    translations: Array<{
      sourceText: string
      translatedText: string
    }>
  }>>('/reading/translation/batch-translate-page', data)
}

/**
 * 上传用户录音
 */
export function uploadUserRecording(data: {
  bookId: number
  pageId: number
  audioFile: File | string
  duration: number
  recordingName?: string
}) {
  return http.post<ApiResponse<{
    id: number
    audioUrl: string
    duration: number
    uploadTime: string
  }>>('/reading/recordings/upload', data)
}

/**
 * 删除用户录音 (更新版本，支持recordingId参数)
 */
export function deleteUserRecordingById(recordingId: number) {
  return http.delete<ApiResponse<boolean>>(`/reading/recordings/${recordingId}`)
}

/**
 * 获取录音详情
 */
export function getRecordingDetail(recordingId: number) {
  return http.get<ApiResponse<{
    id: number
    bookId: number
    pageId: number
    audioUrl: string
    duration: number
    recordingName: string
    createTime: string
  }>>(`/reading/recordings/${recordingId}`)
}

/**
 * 更新录音信息
 */
export function updateRecording(recordingId: number, data: {
  recordingName?: string
}) {
  return http.put<ApiResponse<boolean>>(`/reading/recordings/${recordingId}`, data)
}
